package com.lvmama.pangolin.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lvmama.pangolin.HBaseOper.HotelHBEntityOperation;
import com.lvmama.pangolin.common.Constant;
import com.lvmama.pangolin.common.DateUtil;
import com.lvmama.pangolin.common.RowkeyGenerator;
import com.lvmama.pangolin.common.StringTools;
import com.lvmama.pangolin.entity.ValidateProductListConditionVO;
import com.lvmama.pangolin.entity.hotel.HotelCommodityDetail;
import com.lvmama.pangolin.entity.hotel.HotelCommodityDetailError;
import com.lvmama.pangolin.entity.hotel.HotelProductDetail;
import com.lvmama.pangolin.hotel.service.HotelCommodityDetailErrorService;
import com.lvmama.pangolin.hotel.service.HotelCommodityDetailService;
import com.lvmama.pangolin.hotel.service.HotelProductDetailService;
import net.sf.json.JSONArray;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("validateProduct")
public class HotelValidateProductController {

    private static Logger log = Logger.getLogger(HotelValidateProductController.class);

    @Autowired
    HotelCommodityDetailErrorService hotelCommodityDetailErrorService;

    @Autowired
    HotelCommodityDetailService hotelCommodityDetailService;

    @Autowired
    HotelProductDetailService hotelProductDetailService;

    @Autowired
    HotelHBEntityOperation HotelHBEntityOperation;

    @RequestMapping("hotelValidateProductList")
    public String hotelValidateProductList(ModelMap model, ValidateProductListConditionVO validateProductListConditionVO) throws Exception {
        Map<String, Object> map = new HashMap<>();
        PageHelper.startPage(validateProductListConditionVO.getPage(), validateProductListConditionVO.getPageSize());
        map = getHotelListByVO(map, validateProductListConditionVO);
        PageInfo<HotelCommodityDetailError> page = new PageInfo<HotelCommodityDetailError>(hotelCommodityDetailErrorService.queryLogByMap(map));
        List<HotelCommodityDetailError> Hotel_CommodityDetailList = page.getList();
        model.addAttribute("page", page);
        model.addAttribute("Hotel_CommodityDetailList", Hotel_CommodityDetailList);
        model.addAttribute("validateProductListConditionVO", validateProductListConditionVO);
        if (validateProductListConditionVO.getCompanyCode() != null) {
            if (validateProductListConditionVO.getCompanyCode().startsWith("TC")) {
                return "background/validateProduct/TCValidateProdcuct";
            } else if (validateProductListConditionVO.getCompanyCode().startsWith("XC")) {
                return "background/validateProduct/XCValidateProdcuct";
            } else if (validateProductListConditionVO.getCompanyCode().startsWith("QNR")) {
                return "background/validateProduct/QNRValidateProdcuct";
            } else if (validateProductListConditionVO.getCompanyCode().startsWith("TN")) {
                return "background/validateProduct/TNValidateProdcuct";
            } else {
                return "background/validateProduct/ELValidateProdcuct";
            }
        }
        return null;
    }

    @RequestMapping(value = "/hotelEdit", method = {RequestMethod.GET,
            RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> hotelEdit(HotelCommodityDetailError hotel) {
        Map<String, Object> map = new HashMap<String, Object>(1);
        int code = 1;
        HotelCommodityDetailError hotelCommodityDetailError = null;
        try {
            hotelCommodityDetailError = getHotelByID(hotel);
        } catch (Exception e) {
            log.error("validateProduct...hotelEdit memthod error", e);
            code = 0;
        }
        map.put("code", code);
        map.put("hotelVO", hotelCommodityDetailError);
        return map;

    }

    @RequestMapping("hotelAdd")
    @ResponseBody
    public Map<String, Object> hotelAdd(ModelMap model, HttpServletRequest request, HotelCommodityDetailError hotel) {
        Map<String, Object> map = new HashMap<>();
        String dateVO = request.getParameter("dateVO");
        String taskIDVO = request.getParameter("taskIDVO");
        ValidateProductListConditionVO validateProductListConditionVO = new ValidateProductListConditionVO();
        validateProductListConditionVO.setDateVO(dateVO);
        validateProductListConditionVO.setTaskIDVO(taskIDVO);
        List<HotelCommodityDetailError> Hotel_CommodityDetailList = null;
        PageInfo<HotelCommodityDetailError> page = null;
        Date nowDate = new Date();
        try {
            if (StringTools.isValid(hotel.getId())) {
                hotel.setUpdateTime(nowDate);
                hotelCommodityDetailErrorService.update(hotel);
            }
            PageHelper.startPage(validateProductListConditionVO.getPage(), validateProductListConditionVO.getPageSize());
            map = getHotelListByVO(map, validateProductListConditionVO);
            page = new PageInfo<HotelCommodityDetailError>(hotelCommodityDetailErrorService.queryLogByMap(map));
            Hotel_CommodityDetailList = page.getList();
        } catch (Exception e) {
            log.error("validateProduct...hotelAdd memthod error", e);
            map.put("code", "-1");
        }
        model.addAttribute("page", page);
        model.addAttribute("validateProductListConditionVO", validateProductListConditionVO);
        model.addAttribute("Hotel_CommodityDetailList", Hotel_CommodityDetailList);
        return map;
    }

    @RequestMapping("saveOneHotel")
    @ResponseBody
    public Map<String, Object> saveOneHotel(ModelMap model, HttpServletRequest request, HotelCommodityDetailError hotel) {
        Map<String, Object> map = new HashMap<>();
        String dateVO = request.getParameter("dateVO");
        String taskIDVO = request.getParameter("taskIDVO");
        ValidateProductListConditionVO validateProductListConditionVO = new ValidateProductListConditionVO();
        validateProductListConditionVO.setDateVO(dateVO);
        validateProductListConditionVO.setTaskIDVO(taskIDVO);
        hotel = getHotelByObject(hotel);
        boolean isSave = false;
        try {
            HotelCommodityDetail hotelCommodityDetail = hotelCommodityDetailService.findByProdCommId(hotel.getProductId(), hotel.getCommodityId(), hotel.getCompanyCode());
            //当价格校验失败表中的日期大于等于商品表中的日期时候才更新商品表中该条商品
            if (hotelCommodityDetail != null) {
                if (hotelCommodityDetail.getCreateTime() != null && DateUtil.compare_date(hotel.getCreateTime(), hotelCommodityDetail.getCreateTime()) > 0) {
                    hotel.setId(hotelCommodityDetail.getId());
                    hotelCommodityDetailService.updateByObject(hotel);
                }
            } else {
                HotelProductDetail product = hotelProductDetailService.findByProductId(hotel.getProductId(), hotel.getCompanyCode());
                // 当前商品rowkey
                String rowkey = RowkeyGenerator.generateCommodityRowkeyWithCompany(
                        hotel.getCommodityId(), hotel.getCompanyCode(),
                        product.getComeDate(), hotel.getProductId());
                hotel.setId(rowkey);
                hotelCommodityDetailService.insert(hotel);
            }
            isSave = HotelHBEntityOperation.saveHotelCommodity(hotel, hotel.getId(), Constant.HOTEL_COMMODITY_H, Constant.HB_VARIABLE_FAMILY);
            if (isSave) {
                deleteHotelByObject(hotel);
            }
            map = getHotelListByVO(map, validateProductListConditionVO);
            List<HotelCommodityDetailError> Hotel_CommodityDetailList = null;
            PageInfo<HotelCommodityDetailError> page = null;
            PageHelper.startPage(validateProductListConditionVO.getPage(), validateProductListConditionVO.getPageSize());
            page = new PageInfo<HotelCommodityDetailError>(hotelCommodityDetailErrorService.queryLogByMap(map));
            Hotel_CommodityDetailList = page.getList();
            model.addAttribute("page", page);
            model.addAttribute("Hotel_CommodityDetailList", Hotel_CommodityDetailList);
        } catch (Exception e) {
            log.error("ValidateProductController...saveOneHotel...method..error", e);
            map.put("code", "-1");
        }
        model.addAttribute("validateProductListConditionVO", validateProductListConditionVO);
        return map;
    }

    @RequestMapping("deleteOneHotel")
    public String deleteOneHotel(ModelMap model, HttpServletRequest request, HotelCommodityDetailError hotel) {
        Map<String, Object> map = new HashMap<>();
        String dateVO = request.getParameter("dateVO");
        String taskIDVO = request.getParameter("taskIDVO");
        ValidateProductListConditionVO validateProductListConditionVO = new ValidateProductListConditionVO();
        validateProductListConditionVO.setDateVO(dateVO);
        validateProductListConditionVO.setTaskIDVO(taskIDVO);
        deleteHotelByObject(hotel);
        map = getHotelListByVO(map, validateProductListConditionVO);
        List<HotelCommodityDetailError> Hotel_CommodityDetailList = null;
        PageInfo<HotelCommodityDetailError> page = null;
        try {
            PageHelper.startPage(validateProductListConditionVO.getPage(), validateProductListConditionVO.getPageSize());
            page = new PageInfo<HotelCommodityDetailError>(hotelCommodityDetailErrorService.queryLogByMap(map));
            Hotel_CommodityDetailList = page.getList();
        } catch (Exception e) {
            log.error("ValidateProductController...deleteOneHotel...method...queryLogByMap...error", e);
            map.put("code", "-1");
        }
        model.addAttribute("page", page);
        model.addAttribute("Hotel_CommodityDetailList", Hotel_CommodityDetailList);
        model.addAttribute("validateProductListConditionVO", validateProductListConditionVO);
        return "background/validateProduct/TCValidateProdcuct";
    }

    @RequestMapping("HotelDeleteBatch")
    public String HotelDeleteBatch(ModelMap model, ValidateProductListConditionVO validateProductListConditionVO, String jsonData) {
        Map<String, Object> map = new HashMap<String, Object>();
        JSONArray json = JSONArray.fromObject(jsonData);
        List<HotelCommodityDetailError> hotels = (List<HotelCommodityDetailError>) JSONArray.toCollection(json, HotelCommodityDetailError.class);
        validateProductListConditionVO.setHotelList(hotels);
        map = getHotelListByVO(map, validateProductListConditionVO);
        try {
            hotelCommodityDetailErrorService.deleteHotelByMap(map); //删除全部符合条件数据
        } catch (Exception e) {
            log.error("ValidateProductController...TicketDeleteBatch...method...deleteLogByMap...error ", e);
        }

        PageInfo<HotelCommodityDetailError> page = null;
        List<HotelCommodityDetailError> Hotel_CommodityDetailList = null;
        try {
            PageHelper.startPage(validateProductListConditionVO.getPage(), validateProductListConditionVO.getPageSize());
            page = new PageInfo<HotelCommodityDetailError>(hotelCommodityDetailErrorService.queryLogByMap(map));
            Hotel_CommodityDetailList = page.getList();
        } catch (Exception e) {
            log.error("ValidateProductController...HotelDeleteBatch...method...hotelCommodityDetailErrorService...error", e);
        }
        model.addAttribute("page", page);
        model.addAttribute("Hotel_CommodityDetailList", Hotel_CommodityDetailList);
        model.addAttribute("validateProductListConditionVO", validateProductListConditionVO);
        return "background/validateProduct/TCValidateProdcuct";
    }

    @RequestMapping("HotelSaveBatch")
    public String HotelSaveBatch(ModelMap model, ValidateProductListConditionVO validateProductListConditionVO, String jsonData) throws Exception {
        JSONArray json = JSONArray.fromObject(jsonData);
        List<HotelCommodityDetailError> hotels = (List<HotelCommodityDetailError>) JSONArray.toCollection(json, HotelCommodityDetailError.class);
          validateProductListConditionVO.setHotelList(hotels);
        Map<String, Object> map = new HashMap<String, Object>();
        PageInfo<HotelCommodityDetailError> page = null;
        List<HotelCommodityDetailError> Hotel_CommodityDetailList =  null;
        map = getHotelListByVO(map, validateProductListConditionVO);
        boolean isSave = false;
        try {
            List<HotelCommodityDetailError> hotelList = hotelCommodityDetailErrorService.queryLogByMap(map);
            if (null != hotelList && hotelList.size() > 0) {
                for (HotelCommodityDetailError hotel : hotelList) {

                    HotelCommodityDetail hotelCommodityDetail = hotelCommodityDetailService.findByProdCommId(hotel.getProductId(), hotel.getCommodityId(), hotel.getCompanyCode());
                    if (hotelCommodityDetail != null) {
                        //当价格校验失败表中的日期大于等于商品表中的日期时候才更新商品表中该条商品
                        if (hotelCommodityDetail.getCreateTime() != null && DateUtil.compare_date(hotel.getCreateTime(), hotelCommodityDetail.getCreateTime()) > 0) {
                            hotel.setId(hotelCommodityDetail.getId());
                            hotelCommodityDetailService.updateByObject(hotel);
                        }
                    } else {
                        HotelProductDetail product = hotelProductDetailService.findByProductId(hotel.getProductId(), hotel.getCompanyCode());
                        // 当前商品rowkey
                        String rowkey = RowkeyGenerator.generateCommodityRowkeyWithCompany(
                                hotel.getCommodityId(), hotel.getCompanyCode(),
                                product.getComeDate(), hotel.getProductId());
                        hotel.setId(rowkey);
                        hotelCommodityDetailService.insert(hotel);
                    }
                    // 入hbase
                    isSave = HotelHBEntityOperation.saveHotelCommodity(hotel, hotel.getId(), Constant.HOTEL_COMMODITY_H, Constant.HB_VARIABLE_FAMILY);
                }
            }
            if (isSave) {
                hotelCommodityDetailErrorService.deleteHotelByMap(map); //删除mysql库中符合条件数据
            }
            PageHelper.startPage(validateProductListConditionVO.getPage(), validateProductListConditionVO.getPageSize());
            page = new PageInfo<HotelCommodityDetailError>(hotelCommodityDetailErrorService.queryLogByMap(map));
            Hotel_CommodityDetailList = page.getList();
        } catch (Exception e) {
            log.error("ValidateProductController...HotelSaveBatch...method...hotelCommodityDetailErrorService...error", e);
        }
        model.addAttribute("page", page);
        model.addAttribute("Hotel_CommodityDetailList", Hotel_CommodityDetailList);
        model.addAttribute("validateProductListConditionVO", validateProductListConditionVO);
        return "background/validateProduct/TCValidateProdcuct";

    }

    public Map<String, Object> getHotelListByVO(Map<String, Object> map, ValidateProductListConditionVO validateProductListConditionVO) {
        if (StringTools.isValid(validateProductListConditionVO.getTaskIDVO()) && validateProductListConditionVO.getDateVO().equals("taskID")) {
            map.put("task_id", validateProductListConditionVO.getTaskIDVO());
            log.info("validateProduct controller getHotelListByVO method  task_id=" + validateProductListConditionVO.getTaskIDVO());
        }
        Date endDate = new Date();
        Date startDate = null;
        if (StringTools.isValid(validateProductListConditionVO.getDateVO())) {
            String dateVO = validateProductListConditionVO.getDateVO();
            switch (dateVO) {
                case Constant.DATA_TIME_YEAR:
                    startDate = DateUtil.getDateBeforeYear(endDate);
                    break;
                case Constant.DATA_TIME_QUARTER:
                    startDate = DateUtil.getDateBeforeQuarter(endDate);
                    break;
                case Constant.DATA_TIME_MONTH:
                    startDate = DateUtil.getDateBeforeMonth(endDate);
                    break;
                case Constant.DATA_TIME_WEEK:
                    startDate = DateUtil.getDateBeforeWeek(endDate);
                    break;
                default:
                    break;
            }
        } else if (!StringTools.isValid(validateProductListConditionVO.getDateVO())
                && !StringTools.isValid(validateProductListConditionVO.getTaskIDVO())) {
            startDate = DateUtil.getDateBeforeMonth(endDate); //默认取一个月的数据
        }
        map.put("start_date", startDate);
        map.put("end_date", endDate);
        map.put("company_code", validateProductListConditionVO.getCompanyCode());
        if (null != validateProductListConditionVO.getHotelList() && validateProductListConditionVO.getHotelList().size() > 0) {
            map.put("hotelList", validateProductListConditionVO.getHotelList());
        }
        map.put("page", validateProductListConditionVO.getPage()- 1);
        map.put("pageSize", validateProductListConditionVO.getPageSize());
        log.info("validateProduct controller getHotelListByVO method  start_date=" + startDate);
        return map;
    }

    public HotelCommodityDetailError getHotelByID(HotelCommodityDetailError hotel) {
        Map<String, Object> map = new HashMap<>();
        HotelCommodityDetailError hotelVO = null;
        try {
            if (StringTools.isValid(hotel.getId())) {
                try {
                    hotelVO = hotelCommodityDetailErrorService.findById(hotel.getId());
                } catch (Exception e) {
                    log.error("ValidateProductController...getHotelByID...method...error,id=" + hotel.getId());
                }
            }
        } catch (Exception e) {
            log.error("validateProduct...getHotelByID memthod error", e);
        }
        return hotelVO;
    }

    public HotelCommodityDetailError getHotelByObject(HotelCommodityDetailError hotel) {
        HotelCommodityDetailError hotelVO = null;
        try {
            if (hotel != null) {
                try {
                    hotelVO = hotelCommodityDetailErrorService.findByObject(hotel);
                } catch (Exception e) {
                    log.error("ValidateProductController...getHotelByObject...method...error,id=" + hotel.getId());
                }
            }
        } catch (Exception e) {
            log.error("validateProduct...getHotelByObject memthod error", e);
        }
        return hotelVO;
    }

    public void deleteHotelByObject(HotelCommodityDetailError hotel) {
        if (hotel != null) {
            try {
                hotelCommodityDetailErrorService.deleteByObject(hotel);
            } catch (Exception e) {
                log.error("ValidateProductController...method...deleteHotelByObject...error,commodityId=" + hotel.getCommodityId());
            }
        }
    }
}
